//
//  HYCreateVideoViewController.m
//  XPlayer
//
//  Created by liguoqing on 2023/8/8.
//

#import "HYCreateVideoViewController.h"
#import <BaseWithRAC/BaseModel+LKDBHelper_DLExtension.h>
#import "HYFolderMoverBottomView.h"

@interface HYCreateVideoViewController ()
/// 文件夹所在标识
@property (nonatomic, strong) NSString *folderIdentification;
/// 音频视频的区别标识
@property (nonatomic, assign) BOOL isVideo;
/// 标题
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UITextField *titleField;

@property (nonatomic, strong) UILabel *videoLabel;

@property (nonatomic, strong) UITextField *videoField;

@property (nonatomic, strong) UILabel *imageLabel;

@property (nonatomic, strong) UILabel *imageDescLabel;
/// 视频封面
@property (nonatomic, strong) UIImageView *imageView;
/// 视频时长
@property (nonatomic, strong) NSString *videoDuration;

@property (nonatomic, strong) UILabel *videoTimeLabel;
/// 视频时长
@property (nonatomic, strong) UILabel *durationLabel;

@property (nonatomic, strong) HYFolderMoverBottomView *bottomView;

@property (nonatomic, copy) CreateSuccessBlock successBlock;

@end

@implementation HYCreateVideoViewController

- (instancetype)initWithFolderIdentification:(NSString *)folderIdentification
                                     isVideo:(BOOL)isVideo
{
    self = [super init];
    if(self){
        self.folderIdentification = folderIdentification;
        self.isVideo = isVideo;
    }
    return self;
}

- (void)viewDidLoad 
{
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = self.isVideo?NSLocalizedString(@"新建视频", nil):NSLocalizedString(@"新建音频", nil);
    [self configUI];
    [self bindCommand];
}

- (void)configUI
{
    self.view.backgroundColor = AppBgThemeColor;
    if(!self.isVideo){// 若是音频
        self.titleLabel.text = NSLocalizedString(@"音频标题", nil);
        self.titleField.placeholder = NSLocalizedString(@" 请输入音频标题", nil);
        self.videoLabel.text = NSLocalizedString(@"音频地址", nil);
        self.videoField.placeholder = NSLocalizedString(@" 请输入音频地址", nil);
        self.videoTimeLabel.text = NSLocalizedString(@"音频时长", nil);
        self.durationLabel.text = NSLocalizedString(@"(输入音频地址自动读取回显)", nil);
        self.imageLabel.hidden = YES;
        self.imageDescLabel.hidden = YES;
        self.imageView.hidden = YES;
    }
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.titleField];
    [self.view addSubview:self.videoLabel];
    [self.view addSubview:self.videoField];
    [self.view addSubview:self.videoTimeLabel];
    [self.view addSubview:self.durationLabel];
    [self.view addSubview:self.imageLabel];
    [self.view addSubview:self.imageDescLabel];
    [self.view addSubview:self.imageView];
    [self.view addSubview:self.bottomView];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(self.navigationBarView.mas_bottom).offset(10);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(22);
    }];
    [self.titleField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(5);
        make.left.mas_equalTo(17);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
    }];
    [self.videoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(self.titleField.mas_bottom).offset(15);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(22);
    }];
    [self.videoField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.videoLabel.mas_bottom).offset(5);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
    }];
    [self.videoTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(self.videoField.mas_bottom).offset(15);
        make.height.mas_equalTo(22);
    }];
    [self.durationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.equalTo(self.videoTimeLabel.mas_bottom).offset(10);
        make.height.mas_equalTo(20);
    }];
    
    [self.imageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(self.durationLabel.mas_bottom).offset(15);
        make.height.mas_equalTo(22);
    }];
    [self.imageDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imageLabel.mas_right);
        make.centerY.equalTo(self.imageLabel.mas_centerY);
        make.height.mas_equalTo(20);
    }];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(self.imageLabel.mas_bottom).offset(10);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(80);
    }];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.height.mas_equalTo(64+HOME_BAR_HEIGHT);
    }];
}

- (void)bindCommand
{
    @weakify(self);
    self.bottomView.newBtn.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        [self saveCreateVideoDirectly:NO];
        return [RACSignal empty];
    }];
    self.bottomView.moveBtn.rac_command = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        [self saveCreateVideoDirectly:YES];
        return [RACSignal empty];
    }];
}

#pragma mark - 保存
- (void)saveCreateVideoDirectly:(BOOL)isDirectly
{
    if(!self.titleField.text.length){
        [HYHub showMessage:self.isVideo?NSLocalizedString(@"视频标题不能为空", nil):NSLocalizedString(@"音频标题不能为空", nil)];
        return;
    }
    
    NSString *videoUrl = [self.videoField.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    if(!videoUrl.length){
        [HYHub showMessage:self.isVideo?NSLocalizedString(@"视频播放地址不能为空", nil):NSLocalizedString(@"音频标题不能为空", nil)];
        return;
    }
    BOOL isValid;
    if(self.isVideo){
        isValid = [HYFileManager checkValidVideoPlayUrl:videoUrl];
    }else{
        isValid = [HYFileManager checkValidAudioPlayUrl:videoUrl];
    }
    
    if(!isValid){
        [HYHub showMessage:NSLocalizedString(@"请输入有效播放地址", nil)];
        return;
    }
    /// 新建视频信息
    NSArray *result = [HYHomeVideoModel searchWithWhere:[NSString stringWithFormat:@"videoUrl='%@'",videoUrl] orderBy:nil offset:0 count:0];
    if(result.count){
        [HYHub showMessage:self.isVideo?NSLocalizedString(@"该视频播放地址已创建过", nil):NSLocalizedString(@"音频播放地址已创建过", nil)];
        return;
    }
    if(self.isVideo){
        if(!self.imageView.image){
            [HYHub showMessage:NSLocalizedString(@"获取封面失败,请重新获取", nil)];
            return;
        }
    }
    NSString *lastName = [videoUrl lastPathComponent];
    NSString *firstName = [CommUtls fetchVideoNameWithFullName:lastName];
    if(self.isVideo){
        NSString *imageName = [NSString stringWithFormat:@"%@.png",firstName];
        NSString *imagePath = [HYFileManager videoImageSavePathWithFileName:imageName];
        NSData *imageData = UIImagePNGRepresentation(self.imageView.image);
        BOOL isSuccess = [imageData writeToFile:imagePath atomically:YES];
        if(isSuccess){
            HYHomeVideoModel *videoModel = [[HYHomeVideoModel alloc]init];
            videoModel.folderIdentification = self.folderIdentification;
            NSString *realUrl = [videoUrl componentsSeparatedByString:@"?"].firstObject;
            NSString *suffixName = [realUrl componentsSeparatedByString:@"."].lastObject;
            videoModel.videoTitle = [self.titleField.text stringByAppendingPathExtension:suffixName];
            videoModel.videoUrl = videoUrl;
            videoModel.imageName = imageName;
            videoModel.videoDuration = self.videoDuration;
            NSString *createDate = [CommUtls encodeTimeYearMonthDay:[NSDate date]];
            videoModel.createDate = createDate;
            videoModel.importDate = createDate;
            BOOL isSave = [videoModel saveToDB];
            if(isSave){
                [HYHub showMessage:NSLocalizedString(@"保存成功", nil)];
                if(self.successBlock){
                    self.successBlock(videoModel);
                }
                if(isDirectly){
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }else{
                    self.titleField.text = @"";
                    self.videoField.text = @"";
                    self.durationLabel.text = NSLocalizedString(@"(输入视频地址自动读取回显)", nil);
                    self.imageView.image = nil;
                }
            }else{
                [HYHub showMessage:NSLocalizedString(@"保存失败", nil)];
            }
        }else{
            [HYHub showMessage:NSLocalizedString(@"视频封面写入失败", nil)];
        }
    }else{
        HYHomeVideoModel *videoModel = [[HYHomeVideoModel alloc]init];
        videoModel.folderIdentification = self.folderIdentification;
        NSString *realUrl = [videoUrl componentsSeparatedByString:@"?"].firstObject;
        NSString *suffixName = [realUrl componentsSeparatedByString:@"."].lastObject;
        videoModel.videoTitle = [self.titleField.text stringByAppendingPathExtension:suffixName];
        videoModel.videoUrl = videoUrl;
        videoModel.videoDuration = self.videoDuration;
        videoModel.isAudio = YES;
        NSString *createDate = [CommUtls encodeTimeYearMonthDay:[NSDate date]];
        videoModel.createDate = createDate;
        videoModel.importDate = createDate;
        BOOL isSave = [videoModel saveToDB];
        if(isSave){
            [HYHub showMessage:NSLocalizedString(@"保存成功", nil)];
            if(self.successBlock){
                self.successBlock(videoModel);
            }
            if(isDirectly){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else{
                self.titleField.text = @"";
                self.videoField.text = @"";
                self.durationLabel.text = NSLocalizedString(@"(输入音频地址自动读取回显)", nil);
            }
        }
    }
}

#pragma mark - 生成视频封面
- (void)createVideoCoverImage
{
    BOOL isValid = [HYFileManager checkValidVideoPlayUrl:self.videoField.text];;
    if(!isValid){
        [HYHub showMessage:NSLocalizedString(@"请输入有效播放地址", nil)];
        return;
    }
    if(self.isVideo){
        [HYHub loadMessage:NSLocalizedString(@"视频封面获取中...", nil)];
        NSString *videoUrl = self.videoField.text;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            UIImage *image = [CommUtls fetchVideoCoverImageWithUrl:videoUrl atTime:1.0];
            dispatch_async(dispatch_get_main_queue(), ^{
                [HYHub dismiss];
                if(image){
                    self.imageView.image = image;
                }else{
                    [HYHub showMessage:NSLocalizedString(@"获取视频封面失败", nil)];
                }
            });
        });
    }
}

- (void)textFieldChange:(UITextField *)textField
{
    if(textField.tag == 200){
        // 判断视频地址是否有效
        NSString *videoUrl = textField.text;
        BOOL isValid;
        if(self.isVideo){
            isValid = [HYFileManager checkValidVideoPlayUrl:videoUrl];
        }else{
            isValid = [HYFileManager checkValidAudioPlayUrl:videoUrl];
        }
        NSString *encodeUrl = [videoUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        if(isValid){
            if(self.isVideo){
                [self createVideoCoverImage];
            }
            self.videoDuration = [CommUtls fetchVideoDurationWithUrl:encodeUrl];
            self.durationLabel.text = [NSString stringWithFormat:@"%@：%@",self.isVideo?NSLocalizedString(@"视频时长", nil):NSLocalizedString(@"音频时长", nil),self.videoDuration];
        }
    }
}

- (void)saveAudioOrVideoInfoSuccessBlock:(CreateSuccessBlock)successBlock
{
    self.successBlock = successBlock;
}

#pragma mark - loadLazy
- (UILabel *)titleLabel
{
    if(!_titleLabel){
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.text = NSLocalizedString(@"视频标题", nil);
        _titleLabel.textColor = APPTextThemeColor;
        _titleLabel.font = FONT_BOLD_SIZE(16);
    }
    return _titleLabel;
}

- (UITextField *)titleField
{
    if(!_titleField){
        _titleField = [[UITextField alloc]init];
        _titleField.placeholder = NSLocalizedString(@" 请输入视频标题", nil);
        _titleField.backgroundColor = AppContentBgThemeColor;
        _titleField.tag = 100;
        _titleField.font = FONT_SIZE(16);
        _titleField.layer.cornerRadius = 4.0;
        _titleField.textColor = APPTextThemeColor;
        _titleField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_titleField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _titleField;
}

- (UILabel *)videoLabel
{
    if(!_videoLabel){
        _videoLabel = [[UILabel alloc]init];
        _videoLabel.text = NSLocalizedString(@"视频地址", nil);
        _videoLabel.textColor = APPTextThemeColor;
        _videoLabel.font = FONT_BOLD_SIZE(16);
    }
    return _videoLabel;
}

- (UITextField *)videoField
{
    if(!_videoField){
        _videoField = [[UITextField alloc]init];
        _videoField.placeholder = NSLocalizedString(@" 请输入视频地址", nil);
        _videoField.font = FONT_SIZE(16);
        _videoField.backgroundColor = AppContentBgThemeColor;
        _videoField.tag = 200;
        _videoField.layer.cornerRadius = 4.0;
        _videoField.textColor = APPTextThemeColor;
        _videoField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_videoField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _videoField;
}

- (UILabel *)imageLabel
{
    if(!_imageLabel){
        _imageLabel = [[UILabel alloc]init];
        _imageLabel.text = NSLocalizedString(@"视频封面", nil);
        _imageLabel.textColor = APPTextThemeColor;
        _imageLabel.font = FONT_BOLD_SIZE(16);
    }
    return _imageLabel;
}

- (UILabel *)imageDescLabel
{
    if(!_imageDescLabel){
        _imageDescLabel = [[UILabel alloc]init];
        _imageDescLabel.text = NSLocalizedString(@" (默认视频第一帧)", nil);
        _imageDescLabel.font = FONT_SIZE(14);
        _imageDescLabel.textColor = kLightGrayColor;
    }
    return _imageDescLabel;
}

- (UIImageView *)imageView
{
    if(!_imageView){
        _imageView = [[UIImageView alloc]init];
        _imageView.image = [UIImage imageNamed:@"icon_place_add"];
    }
    return _imageView;
}

- (UILabel *)videoTimeLabel
{
    if(!_videoTimeLabel){
        _videoTimeLabel = [[UILabel alloc]init];
        _videoTimeLabel.text = NSLocalizedString(@"视频时长", nil);
        _videoTimeLabel.textColor = APPTextThemeColor;
        _videoTimeLabel.font = FONT_BOLD_SIZE(16);
    }
    return _videoTimeLabel;
}

- (UILabel *)durationLabel
{
    if(!_durationLabel){
        _durationLabel = [[UILabel alloc]init];
        _durationLabel.text = NSLocalizedString(@"(输入视频地址自动读取回显)", nil);
        _durationLabel.textColor = kLightGrayColor;
        _durationLabel.font = FONT_SIZE(14);
    }
    return _durationLabel;
}

- (HYFolderMoverBottomView *)bottomView
{
    if(!_bottomView){
        _bottomView = [[HYFolderMoverBottomView alloc]initWithTitles:@[NSLocalizedString(@"继续创建", nil),NSLocalizedString(@"直接保存", nil)]];
    }
    return _bottomView;
}

@end
